//
//  HJPlaceholderTextView.swift
//  Micro-blog Sina
//
//  Created by admin on 16/3/31.
//  Copyright © 2016年 admin. All rights reserved.
//

import UIKit

class HJPlaceholderTextView: UITextView {
    
    var placeholder: String? {
        didSet {
            placeholderLabel.text = placeholder
        }
    }
    
    override var font: UIFont? {
        didSet {
            placeholderLabel.font = font
        }
    }
    
    override var text: String? {
        didSet {
            // textView有文本就隐藏
            placeholderLabel.hidden = self.hasText()
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        prepareUI()
        // object: 通知的发送者, nil: 只要发送TextDidChange通知就能监听到. object:指定对象,只有这个对象发送的才能监听到
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textDidChange", name: UITextViewTextDidChangeNotification, object: self)
    }
    
    private func prepareUI() {
        addSubview(placeholderLabel)
        
        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 5))
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 8))
    }
    
    func textDidChange() {
        placeholderLabel.hidden = hasText()
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

    // Mark: - Lazy load
    private lazy var placeholderLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFontOfSize(18)
        label.textColor = UIColor.lightGrayColor()
        label.text = "分享新鲜事..."
        label.sizeToFit()
        return label
    }()
}
